package com.authorize.system.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONObject;
import com.authorize.common.exception.TClientException;
import com.authorize.common.utils.PayUtils;
import com.authorize.system.domain.APayConfig;
import com.authorize.system.service.IAPayConfigService;
import com.authorize.system.service.ISysConfigService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.authorize.common.annotation.Log;
import com.authorize.common.core.controller.BaseController;
import com.authorize.common.core.domain.AjaxResult;
import com.authorize.common.enums.BusinessType;
import com.authorize.system.domain.AOrder;
import com.authorize.system.service.IAOrderService;
import com.authorize.common.utils.poi.ExcelUtil;
import com.authorize.common.core.page.TableDataInfo;

/**
 * 订单管理Controller
 *
 * @author zwb
 * @date 2024-01-30
 */
@RestController
@RequestMapping("/system/order")
public class AOrderController extends BaseController
{
    @Autowired
    private IAOrderService aOrderService;

    @Autowired
    private IAPayConfigService aPayConfigService;

    @Autowired
    private ISysConfigService configService;

    /**
     * 查询订单管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(AOrder aOrder)
    {
        startPage();
        List<AOrder> list = aOrderService.selectAOrderList(aOrder);
        return getDataTable(list);
    }

    /**
     * 导出订单管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:order:export')")
    @Log(title = "订单管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AOrder aOrder)
    {
        List<AOrder> list = aOrderService.selectAOrderList(aOrder);
        ExcelUtil<AOrder> util = new ExcelUtil<AOrder>(AOrder.class);
        util.exportExcel(response, list, "订单管理数据");
    }

    /**
     * 获取订单管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:order:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(aOrderService.selectAOrderById(id));
    }

    /**
     * 新增订单管理
     */
    @PreAuthorize("@ss.hasPermi('system:order:add')")
    @Log(title = "订单管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AOrder aOrder) throws TClientException {
        return toAjax(aOrderService.insertAOrder(aOrder));
    }

    /**
     * 修改订单管理
     */
    @PreAuthorize("@ss.hasPermi('system:order:edit')")
    @Log(title = "订单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AOrder aOrder) throws TClientException {
        return toAjax(aOrderService.updateAOrder(aOrder));
    }

    /**
     * 删除订单管理
     */
    @PreAuthorize("@ss.hasPermi('system:order:remove')")
    @Log(title = "订单管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(aOrderService.deleteAOrderByIds(ids));
    }

    /**
     * 订单退款
     */
    @PreAuthorize("@ss.hasPermi('system:order:edit')")
    @Log(title = "订单管理", businessType = BusinessType.UPDATE)
    @PostMapping("/refund")
    public void refund(@RequestBody AOrder aOrder) throws TClientException {
        //查询支付渠道
        APayConfig aPayConfig = aPayConfigService.selectAPayConfigById(aOrder.getPayId());
        if(aPayConfig == null){
            throw new TClientException("退款失败，支付渠道获取失败");
        }
        try{
            JSONObject params = new JSONObject();
            params.put("outTradeNo",aOrder.getOutTradeNo());
            params.put("refundMoney",String.valueOf(aOrder.getPrice()));
            Map<String,String> headers = new HashMap<>();
            headers.put("appid",aPayConfig.getAppId());
            String p = JSONObject.toJSONString(params);
            String sign = PayUtils.getSign(p,aPayConfig.getSginKey());
            headers.put("sign",sign);
            String payUrl = configService.selectConfigByKey("sys.payUrl");
            //请求退款接口
            String result = PayUtils.doPost(payUrl+"/open/api/refund",p,headers);
            JSONObject json = JSONObject.parseObject(result);
            if(json == null || json.getInteger("code") != 200){
                throw new TClientException("退款出现异常，请稍后重试！");
            }
            aOrder.setStatus(4);
            aOrder.setRefundMoney(aOrder.getPrice());
            aOrder.setUpdateTime(new Date());
            aOrderService.updateAOrder(aOrder);
        }catch (Exception e){
            e.printStackTrace();
            throw new TClientException("退款失败，出现未知异常");
        }
    }
}
